﻿using System;
using System.IO;
using System.Messaging;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Windows.Forms;
using PowerAwareBluetooth.Controller.IO;
using PowerAwareBluetooth.Controller.Manager;
using PowerAwareBluetooth.Model;
using PowerAwareBluetooth.Model.Process;
using PowerAwareBluetooth.View;
using System.Diagnostics;

namespace PowerAwareBluetooth_UI.View
{
    /// <summary>
    /// The UI main form that allows the user to change the rules, clear the DB, and
    /// start and stop the manager.
    /// </summary>
    public partial class MainForm : Form
    {
        private bool m_IsClosingManager = false;

        /// <summary>
        /// constructor
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
        }

        #region /// Event Handlers ///

        /// <summary>
        /// opends the rules-list 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rulesButton_Click(object sender, EventArgs e)
        {
            UserRulesForm userRulesForm = new UserRulesForm();
//            userRulesForm.BindedRuleList = m_BluetoothPowerManager.RulesList;

            userRulesForm.ShowDialog();
        }

        /// <summary>
        /// stars the manager
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void startManagerButton_Click(object sender, EventArgs e)
        {
            RunManager();
        }

        /// <summary>
        /// stops the manager
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void stopManagerButton_Click(object sender, EventArgs e)
        {
            NotifyCloseManager();
        }

        #endregion

        /// <summary>
        /// runs the blue-tooth manager
        /// </summary>
        private void RunManager()
        {
            bool? managerIsRunning = BluetoothPowerManager.ManagerIsRunning(true, false);
            if (managerIsRunning.HasValue)
            {
                if (!managerIsRunning.Value)
                {
                    try
                    {
                        string myPath = Path.Combine(IOManager.CurrentDirectory, BluetoothPowerManager.ManagerProcessName);
                        System.Diagnostics.Process.Start(myPath, null);
                        SetMessageLabel("Manager started...");
                        



                    }
                    catch (Exception e)
                    {
                        string message = "Unable to start the manger:\n" + e.Message;
                        MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                                        MessageBoxDefaultButton.Button1);
                    }
                }
                else
                {
                    SetMessageLabel("Manager is already running...");
                }
            }
        }

        /// <summary>
        /// sets the label with the given text, the label will be cleared after 3.5 seconds
        /// </summary>
        /// <param name="text">text to put on the label</param>
        private void SetMessageLabel(string text)
        {
            m_MessageLabel.Text = text;
            m_TimerClearTable.Enabled = true;
        }

        /// <summary>
        /// notifies the blue-tooth process that a new rules list
        /// is ready.
        /// </summary>
        private void NotifyCloseManager()
        {
            bool? managerIsRunning = BluetoothPowerManager.ManagerIsRunning(true, false);
            if (managerIsRunning.HasValue)
            {
                if (managerIsRunning.Value)
                {
                    m_IsClosingManager = true;
                    SetMessageLabel("Closing manager...");
                    WinMessageAdapter.NotifyCloseManager();
                }
                else
                {
                    SetMessageLabel("Manager is not running...");
                }  
            }
        }

        /// <summary>
        /// notifies the blue-tooth process that a new rules list
        /// is ready.
        /// </summary>
        private void NotifyResetLearning()
        {
            WinMessageAdapter.NotifyResetLearning();
        }

        /// <summary>
        /// deletes the learning file DB and notifies the manager
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void resetLearningButton_Click(object sender, EventArgs e)
        {
            IOManager.TryDelete(IOManager.SaveType.LEARNED_TIMELINE);
            NotifyResetLearning();
            SetMessageLabel("Learning DB was cleared...");
        }

        /// <summary>
        /// removes the text from the label and stops the timer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_TimerClearTable_Tick(object sender, EventArgs e)
        {
            if (m_IsClosingManager)
            {
                bool? managerIsRunning = BluetoothPowerManager.ManagerIsRunning(true, false);
                if (managerIsRunning.HasValue)
                {
                    if (managerIsRunning.Value)
                    {
                        // do nothing
                        return;
                    }
                }
                m_IsClosingManager = false;
            }
            m_MessageLabel.Text = string.Empty;
            m_TimerClearTable.Enabled = false;
        }

        private const int WM_SYSCOMMAND = 0x0112;
        private const int SC_MINIMIZE = 0xF020; 


    }
}